package com.liuwei.spring.cloud.common.utils;/**
 * @author : HtmlHelper
 * @version V1.0
 * @date: 2023/12/29 1:03 PM
 * @Description: TODO
 */

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.system.SystemUtil;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontProvider;
import gui.ava.html.image.generator.HtmlImageGenerator;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author : HtmlHelper
 * @version V1.0
 * @date: 2023/12/29 1:03 PM
 * @Description: TODO
 */
public class HtmlHelper {

    public static void convert2Pdf(String htmlContent, OutputStream outputStream) {
        try (PdfWriter pdfWriter = new PdfWriter(outputStream)) {
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);
            pdfDocument.setDefaultPageSize(PageSize.A4);

            // 字体设置，解决中文不显示问题
            FontProvider fontProvider = new FontProvider();
            PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H");
            fontProvider.addFont(sysFont.getFontProgram(), "UniGB-UCS2-H");

            ConverterProperties properties = new ConverterProperties();
            properties.setFontProvider(fontProvider);
            HtmlConverter.convertToPdf(htmlContent, pdfDocument, properties);
            pdfDocument.close();
        } catch (Exception e) {
            throw new RuntimeException("PFD文件生成失败", e);
        }
    }

    public static void convert2Image(String htmlContent, File targetJpg, boolean trimImage) throws Exception {
        File pdf = FileUtil.createTempFile(new File(SystemUtil.USER_DIR));
        convert2Pdf(htmlContent,new FileOutputStream(pdf));
        PdfHelper.convertToImage(pdf,targetJpg,Integer.MAX_VALUE);
        if(trimImage){
            BufferedImage source = ImageHelper.readImage(targetJpg);
            BufferedImage transfer = ImageHelper.getTrimImage(source,20);
            ImageHelper.saveImage(targetJpg,transfer,"jpg");
        }
    }

    public static void main(String[] args) throws Exception {
        String url = "https://www.hao123.com/";
        String html = HttpUtil.get(url);
        File image = new File("/Users/liuwei19/temp/baidu.jpg");
        convert2Image(html,image,true);
    }

}
